﻿using ImageManager.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using System.Text;

namespace ImageManager.ImageApi.AuthenticationInjection
{
    public class MyAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
    {
        IMyFailureReason reason;
        public MyAuthorizationMiddlewareResultHandler(IMyFailureReason reason)
        {
            this.reason = reason;
        }
        private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();

        public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
        {
            await defaultHandler.HandleAsync(next, context, policy, authorizeResult);
            if (authorizeResult.Succeeded) return;
            if (reason != null)
            {
                context.Response.StatusCode = (int)reason.GetStatusCode();
                var resultData = new ResponseData<String>("操作失败");
                resultData.SystemCode = 0;
                resultData.Message = reason.GetMessage();
                var msg = Encoding.UTF8.GetBytes(Utils.Serialize(resultData));
                await context.Response.Body.WriteAsync(msg, 0, msg.Length);
            }
        }
    }
}
